/*
 * @Description: 用于管理table中某行操作的状态 如删除、切换状态
 * @Author: liyuhao
 * @Date: 2021-07-21 10:26:32
 * @LastEditors: liyuhao
 * @LastEditTime: 2021-07-21 10:26:49
 */
import {useCallback, useRef} from 'react'
import {useRequest} from 'ahooks'

type Service<R, P> = (params: P) => Promise<R>

const useTableOperation: (service: Service<any, any>, onSuccess?: Function) => {
    isLoading: (id: (number | string)) => boolean;
    run: (params: any, id: any) => void
} = (service, onSuccess) => {
    const operationId = useRef(null)
    const {loading, run: _run} = useRequest(service, {
        manual: true,
        onSuccess: res => {
            onSuccess && onSuccess(res)
        }
    })

    const run = useCallback((params: any, id: any) => {
        operationId.current = id
        return _run(params)
    }, [_run])

    const isLoading = useCallback((id: number | string) => {
        return loading && id === operationId.current
    }, [loading])

    return {
        isLoading,
        run,
    }
}

export default useTableOperation